package leetcode.leetcode102;

import queue.queue.LinkedListQueue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author czt
 * @version 1.0
 * @since 2024/12/19
 *
 * 树层遍历二叉树
 */
public class Leetcode102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            List<Integer> currentLevel = new ArrayList<>();

            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll(); // 从队列中获取节点
                currentLevel.add(node.val); // 添加节点值到当前层

                // 将左右子节点加入队列
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }

            result.add(currentLevel); // 将当前层的结果加入最终结果
        }

        return result;
    }

    public static void main(String[] args) {
        LinkedList<Object> objects = new LinkedList<>();
    }
}
